package net.javaonfly.core.dispatch;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.javaonfly.core.controller.SelfRenderContrallor;
import net.javaonfly.core.exception.JofException;
import net.javaonfly.core.view.Render;

public class Dispatcher {
	private Router router;

	private String pkg;

	public Dispatcher(String pkg) {
		router = new Router();
		this.pkg = pkg;
	}

	/**
	 * @param url
	 * @param input
	 * @param output
	 * @param session
	 * @return
	 * @throws JofException
	 */
	public String dispatch(String url, Map input, Map output, Map session,
			HttpServletRequest request, HttpServletResponse response)
			throws JofException {
		HandlerRouteExt handlerRouteExt = router.resolve(url, pkg);
		Method action = handlerRouteExt.getHandlerRoute().getAction();
		try {
			Object controller = handlerRouteExt.getHandlerRoute()
					.getController().newInstance();
			if (controller instanceof SelfRenderContrallor) {
				Render render = new Render(request, response);
				((SelfRenderContrallor) controller).setRender(render);
			}
			String redirect = (String) action.invoke(controller,
					handlerRouteExt.getId(), input, output, session);
			if (!(controller instanceof SelfRenderContrallor)) {
				if (null == redirect)
					return handlerRouteExt.getHandlerRoute().getTemplate();
				else {
					return redirect;
				}
			}else{
				return null;
			}
		} catch (Exception e) {
			throw new JofException("action invoke error, url: " + url, e);
		}
	}
}
